package mysql

import (
	"database/sql"
	"errors"
	"log"
	"news/models"
	"strings"

	"github.com/jmoiron/sqlx"

	"go.uber.org/zap"
)

var ErrorInsertFailed = errors.New("插入数据失败")
var ErrorQueryFailed = errors.New("查询失败")

func CreateInsertPost(p *models.Post) (err error) {
	sqlStr := "insert into" +
		" post(post_id ,title,content,author_id,community_id,status)" +
		" values(?,?,?,?,?,?)"
	_, err = db.Exec(sqlStr, p.PostID, p.Title, p.Content, p.AuthorId,
		p.CommunityID, p.Status)
	if err != nil {
		zap.L().Error("community inset data failed", zap.Error(err))
		return ErrorInsertFailed
	}
	return err

}

// 社区与post 的关联关系 //查询所有社区分类
func GetCommunityInfo() (communityList []*models.CommunityPost, err error) {
	sqlStr := "select community_id, community_name from community"
	err = db.Select(&communityList, sqlStr)
	if err == sql.ErrNoRows {
		err = nil
		zap.L().Warn("there is no community in db")
		return
	}
	return
}

// 社区与post 的关联关系 # 通过 社区的  community_id 获取 post community_id 的信息
func GetPostInfoList(id int64) (postList []*models.PostCommunity, err error) {
	sqlStr := "select " +
		"post_id, title, content, author_id, community_id, create_time " +
		"from post " +
		"where community_id = ?"
	err = db.Select(&postList, sqlStr, id)
	if err == sql.ErrNoRows {
		err = nil
		zap.L().Warn("there is no post in db")
		return
	}
	return
}

//根据ID 获取 post 的详情
func GetPostById(pid int64) (data *models.Post, err error) {
	data = new(models.Post)
	sqlstr := `select
			post_id, title, content, author_id, community_id,create_time 
			from post
			where post_id = ?
			`
	err = db.Get(data, sqlstr, pid)
	if err == sql.ErrNoRows || err != nil {
		err = nil
		zap.L().Warn("there is no post in db")
		return nil, ErrorQueryFailed
	}
	return
}

// 获取post 所有信息
func GetPostAll(p *models.Post, page, size int64) (dataInfo []*models.Post, err error) {
	id := p.CommunityID
	log.Println(id)
	sqlStr := `select
			post_id, title, content, author_id, community_id,create_time 
			from post limit ? ,?
			`
	err = db.Select(&dataInfo, sqlStr, (page-1)*size, size)
	if err != nil {
		zap.L().Error("db.Select(&dataInfo, sqlStr)", zap.Error(err))
		return
	}
	return
}

// 根据 redis 里获取到的ｉｄｓ　进行对数据的查询
func GetPostListByIds(ids []string) (postList []*models.Post, err error) {
	sqlStr := `select post_id, title, content, author_id, community_id, create_time
	from post
	where post_id in (?)
	order by FIND_IN_SET(post_id, ?)`
	// 动态填充id
	query, args, err := sqlx.In(sqlStr, ids, strings.Join(ids, ","))
	if err != nil {
		return
	}
	query = db.Rebind(query)
	err = db.Select(&postList, query, args...)
	return
}
